<template>
  <div ref="chartRef" style="height: 100%; width: 100%"></div>
</template>

<script setup lang="ts">
import * as echarts from "echarts";
import { onMounted, onUnmounted, shallowRef, watch } from "vue";

const props = defineProps(["option"]);

// 使用 shallowRef 来创建一个对 div 元素的引用
const chartRef = shallowRef(null);

let chartInstance: echarts.ECharts | null = null;

// 初始化图表
const initChart = () => {
  if (!chartRef.value) {
    console.error("图表容器不可用。");
    return;
  }
  if (chartInstance) {
    // 防止重复初始化
    return;
  }
  try {
    chartInstance = echarts.init(chartRef.value);
    chartInstance.setOption(props.option);
  } catch (error) {
    console.error("无法加载图表：", error);
  }
};

// 当组件挂载时调用的函数，用于初始化图表并添加窗口大小调整的监听器
onMounted(() => {
  initChart();
  const handleResize = () => {
    if (chartInstance) {
      chartInstance.resize();
    }
  };
  // 监听窗口大小改变，并重新调整图表大小
  window.addEventListener("resize", handleResize);

  // 当组件卸载时调用的函数，用于清理资源
  onUnmounted(() => {
    if (chartInstance) {
      chartInstance.dispose();
      chartInstance = null;
    }
    window.removeEventListener("resize", handleResize);
  });
});

// 监听 props.option 的变化，以更新图表选项
watch(
  () => props.option,
  (newOption: echarts.EChartsOption) => {
    if (chartInstance) {
      chartInstance.setOption(newOption);
      chartInstance.resize();
    }
  }
);
</script>
